package com.jinchengll.xigua.ui.fragment;

import android.content.pm.ActivityInfo;
import android.view.View;
import android.widget.FrameLayout;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.dueeeke.videocontroller.StandardVideoController;
import com.dueeeke.videocontroller.component.CompleteView;
import com.dueeeke.videocontroller.component.ErrorView;
import com.dueeeke.videocontroller.component.GestureView;
import com.dueeeke.videocontroller.component.TitleView;
import com.dueeeke.videocontroller.component.VodControlView;
import com.dueeeke.videoplayer.player.VideoView;
import com.dueeeke.videoplayer.player.VideoViewManager;
import com.jinchengll.xigua.R;
import com.jinchengll.xigua.constant.VideoPlayerTag;
import com.jinchengll.xigua.entity.Video;
import com.jinchengll.xigua.ui.adapter.RecommendRecyclerViewAdapter;
import com.jinchengll.xigua.ui.base.BaseFragment;
import com.jinchengll.xigua.ui.listener.OnItemChildClickListener;
import com.jinchengll.xigua.ui.viewmodel.RecommendViewModel;
import com.jinchengll.xigua.util.Utils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import java.util.ArrayList;

public class RecommendFragment extends BaseFragment implements OnItemChildClickListener {

    private final String TAG = "RecommendFragment";

    private RecommendViewModel viewModel;

    private RecyclerView recyclerView;
    private RefreshLayout refreshLayout;
    private LinearLayoutManager layoutManager;

    // 视频播放相关组件
    protected VideoView mVideoView;
    protected StandardVideoController mController;
    protected ErrorView mErrorView;
    protected CompleteView mCompleteView;
    protected TitleView mTitleView;

    public RecommendFragment() {
    }

    public static RecommendFragment newInstance() {
        return new RecommendFragment();
    }

    @Override
    protected void initData() {
        viewModel = getViewModel(RecommendViewModel.class);
        // 初始化，给个空数据
        RecommendRecyclerViewAdapter adapter =
                new RecommendRecyclerViewAdapter(new ArrayList<>(), getContext());
        adapter.setOnItemChildClickListener(this);
        recyclerView.setAdapter(adapter);
        recyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(View view) {

            }
            @Override
            public void onChildViewDetachedFromWindow(View view) {
                FrameLayout playerContainer = view.findViewById(R.id.playerContainer);
                View v = playerContainer.getChildAt(0);
                if (v != null && v == mVideoView && !mVideoView.isFullScreen()) {
                    releaseVideoView();
                }
            }
        });

        viewModel.videoListLD.observe(this, videoList -> {
            adapter.setVideoList(videoList);
            adapter.notifyDataSetChanged();
        });
        // 设置上下拉刷新
        refreshLayout.setOnRefreshListener(layout -> {
            viewModel.getViewPage(true);
            layout.finishRefresh(true);
        });
        refreshLayout.setOnLoadMoreListener(layout -> {
            viewModel.getViewPage(false);
            layout.finishLoadMore(true);
        });
        viewModel.getViewPage(true);
    }

    @Override
    protected void initView(View view) {
        recyclerView = view.findViewById(R.id.recommendRecyclerView);
        refreshLayout = view.findViewById(R.id.recommendRefreshLayout);
        layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        initVideoView();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_recommend;
    }

    protected void initVideoView() {
        mVideoView = new VideoView(getActivity());
        mVideoView.setOnStateChangeListener(new com.dueeeke.videoplayer.player.VideoView.SimpleOnStateChangeListener() {
            @Override
            public void onPlayStateChanged(int playState) {
                //监听VideoViewManager释放，重置状态
                if (playState == com.dueeeke.videoplayer.player.VideoView.STATE_IDLE) {
                    Utils.removeViewFormParent(mVideoView);
                    viewModel.mLastPos = viewModel.mCurPos;
                    viewModel.mCurPos = -1;
                }
            }
        });
        mController = new StandardVideoController(getActivity());
        mErrorView = new ErrorView(getActivity());
        mController.addControlComponent(mErrorView);
        mCompleteView = new CompleteView(getActivity());
        mController.addControlComponent(mCompleteView);
        mTitleView = new TitleView(getActivity());
        mController.addControlComponent(mTitleView);
        mController.addControlComponent(new VodControlView(getActivity()));
        mController.addControlComponent(new GestureView(getActivity()));
        mController.setEnableOrientation(true);
        mVideoView.setVideoController(mController);
    }

    @Override
    public void onPause() {
        super.onPause();
        pause();
    }

    /**
     * 由于onPause必须调用super。故增加此方法，
     * 子类将会重写此方法，改变onPause的逻辑
     */
    protected void pause() {
        releaseVideoView();
    }

    @Override
    public void onResume() {
        super.onResume();
        resume();
    }

    /**
     * 由于onResume必须调用super。故增加此方法，
     * 子类将会重写此方法，改变onResume的逻辑
     */
    protected void resume() {
        if (viewModel.mLastPos == -1)
            return;
        //恢复上次播放的位置
        startPlay(viewModel.mLastPos);
    }

    /**
     * PrepareView被点击
     */
    @Override
    public void onItemChildClick(int position) {
        startPlay(position);
    }

    /**
     * 开始播放
     *
     * @param position 列表位置
     */
    protected void startPlay(int position) {
        if (viewModel.mCurPos == position) return;
        if (viewModel.mCurPos != -1) {
            releaseVideoView();
        }

        Video video = viewModel.videoListLD.getValue().get(position);
        mVideoView.setUrl(video.getPlayUrl());
        mTitleView.setTitle(video.getVtitle());
        View itemView = layoutManager.findViewByPosition(position);
        if (itemView == null) return;
        RecommendRecyclerViewAdapter.RecommendViewHolder viewHolder =
                (RecommendRecyclerViewAdapter.RecommendViewHolder) itemView.getTag();
        //把列表中预置的PrepareView添加到控制器中，注意isPrivate此处只能为true。
        mController.addControlComponent(viewHolder.mPrepareView, true);
        Utils.removeViewFormParent(mVideoView);
        viewHolder.mPlayerContainer.addView(mVideoView, 0);
        //播放之前将VideoView添加到VideoViewManager以便在别的页面也能操作它
        getVideoViewManager().add(mVideoView, VideoPlayerTag.LIST);
        mVideoView.start();
        viewModel.mCurPos = position;
    }

    protected VideoViewManager getVideoViewManager() {
        return VideoViewManager.instance();
    }

    private void releaseVideoView() {
        mVideoView.release();
        if (mVideoView.isFullScreen()) {
            mVideoView.stopFullScreen();
        }
        if (getActivity().getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        viewModel.mCurPos = -1;
    }
}